import 'dart:async';
import 'package:flutter/material.dart';
import 'package:qgchat/common/class/overlay/index.dart';
import 'package:qgchat/http/apis/video.dart';
import 'package:qgchat/http/models/giftlistModel.dart';
import 'package:svgaplayer_flutter/player.dart';
import 'package:svgaplayer_flutter/svgaplayer_flutter.dart';

/// 礼物动画
/// todo 点击可以取消动画（坑点在疯狂取消时会有问题）
class GitfSvga {
  static const Duration delayed = Duration(milliseconds: 3500); // 礼物持续时间
  static const Duration delayedEnd = Duration(milliseconds: 1000); // 礼物播放后等待时间
  static OverlayEntry overlayEntry; // 礼物
  static Timer _timer; // 动画显示定时器
  static bool canRun = true; // 可以播放礼物
  static bool dismissed = false; // 已经销毁礼物
  static List<GiftlistModel> giftlist; // 礼物列表

  /// 显示礼物
  static show(int id) async {
    // 正在显示拦截
    if (!canRun) {
      return;
    }
    // 获取礼物列表拦截
    if (giftlist == null) {
      await toGetGiftlist();
    }

    dismiss();
    dismissed = false;
    canRun = false;
    overlayEntry = OverlayEntry(builder: (context) {
      int i = giftlist.indexWhere((item) => item.id == id);
      return _GiftSvgaWidget(i + 1, () async {
        // dismiss();
        // canRun = true;
      });
    });

    appOverlayState.insert(overlayEntry);

    _timer = Timer(delayed, () async {
      dismiss();
      canRun = true;
    });
  }

  /// 销毁礼物
  static dismiss() {
    if (dismissed) {
      return;
    }
    dismissed = true;
    _timer?.cancel();
    overlayEntry?.remove();
  }

  /// 获取礼物
  static toGetGiftlist() async {
    giftlist = await VideoApis.giftlist();
  }
}

/// 动画礼物组件
class _GiftSvgaWidget extends StatefulWidget {
  _GiftSvgaWidget(this.id, this.click, {Key key}) : super(key: key);

  final int id;
  final Function click;

  @override
  __GiftSvgaWidgetState createState() => __GiftSvgaWidgetState();
}

class __GiftSvgaWidgetState extends State<_GiftSvgaWidget>
    with SingleTickerProviderStateMixin {
  SVGAAnimationController animationController; // svga动画控制器

  @override
  void initState() {
    super.initState();
    animationController = SVGAAnimationController(vsync: this);
    SVGAParser.shared
        .decodeFromAssets("assets/svga/gift${widget.id}.svga")
        .then((videoItem) {
      animationController
        ..videoItem = videoItem
        ..repeat();
    });
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return FlatButton(
      padding: EdgeInsets.zero,
      onPressed: widget.click,
      child: Material(
        color: Colors.white.withOpacity(0),
        child: Container(
          child: SVGAImage(animationController),
        ),
      ),
    );
  }
}
